
#import "DnpEquipmentKeychain.h"

@implementation DnpEquipmentKeychain

static NSString * const secAttrService = @"com.dnp.keychain.service";

+ (instancetype)sharedInstance {
    static DnpEquipmentKeychain *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}


- (BOOL)saveData:(NSString *)text {
    
    NSData *convertText = [text dataUsingEncoding:NSUTF8StringEncoding];
    if (!convertText) {
        return NO;
    }
    
    NSDictionary *dic = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: secAttrService,
        (__bridge id)kSecValueData: convertText
    };
    
    SecItemDelete((__bridge CFDictionaryRef)dic);
    
    return SecItemAdd((__bridge CFDictionaryRef)dic, NULL) == errSecSuccess;
}

- (NSString *)getData {
    
    NSDictionary *dic = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: secAttrService,
        (__bridge id)kSecReturnData: (__bridge id)kCFBooleanTrue,
        (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne
    };
    
    CFTypeRef typeObject = NULL;
    OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef)dic, &typeObject);
    
    if (osStatus == errSecSuccess) {
        NSData *resultData = (__bridge_transfer NSData *)typeObject;
        return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }
    
    return nil;
}

@end
